/**
 * 七牛云nodejs文档地址：https://developer.qiniu.com/kodo/sdk/1289/nodejs#upload-flow
 */
const Qiniu = require("qiniu");
const config = require("../config/qiniu");

const mac = new Qiniu.auth.digest.Mac(config.ACCESS_KEY, config.SECRET_KEY);
const qconfig = new Qiniu.conf.Config();
// 空间对应的机房
qconfig.zone = Qiniu.zone[config.ZONE];
const formUploader = new Qiniu.form_up.FormUploader(qconfig);

/**
 * 生成上传token
 * @param {String} bucket 上传的空间名
 * @param {String} key 上传到七牛后保存的文件名
 * @return {*}
 */
function generateUptoken(bucket, key) {
  const option = {
    scope: bucket
    // 自定义回调地址
    // callbackUrl: 'http://api.example.com/qiniu/upload/callback',
    // callbackBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}',
    // callbackBodyType: 'application/json'
  };
  const putPolicy = new Qiniu.rs.PutPolicy(option);
  return putPolicy.uploadToken(mac);
}

/**
 * 上传文件
 * @param {String} uptoken 上传的token
 * @param {String} key 上传到七牛后保存的文件名
 * @param {String} localFilePath 本地文件路径
 */
function uploadFile(uptoken, key, localFilePath) {
  return new Promise((resolve, reject) => {
    const putExtra = new Qiniu.form_up.PutExtra();
    // 文件上传
    formUploader.putFile(uptoken, key, localFilePath, putExtra, function(
      respErr,
      rep,
      respInfo
    ) {
      if (respErr) throw respErr;
      if (respInfo.statusCode === 200) {
        resolve(`http://${config.BUCKET}.${config.DOMAIN}/${rep.key}`);
        return;
      }
      console.error("上传失败：", respInfo.statusCode, ", ", rep);
      reject({ message: "上传失败", code: respInfo.statusCode });
    });
  });
}

module.exports = {
  generateUptoken,
  uploadFile
};
